import {
  Shader,
  ShaderData,
  ShaderProperty,
  ShaderPool,
  ShaderProgram,
  ShaderProgramPool,
  ShaderMacro,
  ShaderMacroCollection,
  ShaderDataGroup,
  ShaderLib
} from "@nirvana/shaders";
import { Color } from "@nirvana/math";

import { WebGLCanvas } from "@nirvana/canvas";
import { VertexBufferData, IndexBufferData, DataElement } from "@nirvana/core";

const shaderMacroCollection: ShaderMacroCollection = new ShaderMacroCollection();
console.log(shaderMacroCollection);
const colorShaderData: ShaderData = new ShaderData(ShaderDataGroup.Material);
console.log(ShaderDataGroup, colorShaderData);
const pool: ShaderProgramPool = new ShaderProgramPool();

// 使用使用 Canvas
let canvas = document.getElementById("engine-nirvana");
const webCanvas = new WebGLCanvas(canvas, {});
const engine = webCanvas.engine;
const gl = engine.gl;

const cVS = `
attribute vec3 position;
attribute vec3 color;
varying vec3 vColor;
void main(void) { 
  gl_Position = vec4(position, 1.);
  vColor = color;
}
`;
const cFS = `
varying vec3 vColor;
void main(void) {
  gl_FragColor = vec4(vColor, 1.);
}`;
const colorDemo = Shader.create("colorDemo", cVS, cFS);
console.log(colorDemo, Shader.find("colorDemo"));

const colorProgram: ShaderProgram = colorDemo.getShaderProgram(engine.gl, shaderMacroCollection, pool);
console.log("color", colorProgram);

const vBuffer = new VertexBufferData(
  new Float32Array([
    -0.5,-0.5,-0.5, 0.5,-0.5,-0.5, 0.5, 0.5,-0.5, -0.5, 0.5,-0.5,
    -0.5,-0.5, 0.5, 0.5,-0.5, 0.5, 0.5, 0.5, 0.5, -0.5, 0.5, 0.5,
    -0.5,-0.5,-0.5, -0.5, 0.5,-0.5, -0.5, 0.5, 0.5, -0.5,-0.5, 0.5,
    0.5,-0.5,-0.5, 0.5, 0.5,-0.5, 0.5, 0.5, 0.5, 0.5,-0.5, 0.5,
    -0.5,-0.5,-0.5, -0.5,-0.5, 0.5, 0.5,-0.5, 0.5, 0.5,-0.5,-0.5,
    -0.5, 0.5,-0.5, -0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5,-0.5, 
  ]),
  [new DataElement("position", 3, gl.FLOAT, false, 0, 0)]
);
const cBuffer = new VertexBufferData(
  new Float32Array([
    5,3,7, 5,3,7, 5,3,7, 5,3,7,
    1,1,3, 1,1,3, 1,1,3, 1,1,3,
    0,0,1, 0,0,1, 0,0,1, 0,0,1,
    1,0,0, 1,0,0, 1,0,0, 1,0,0,
    1,1,0, 1,1,0, 1,1,0, 1,1,0,
    0,1,0, 0,1,0, 0,1,0, 0,1,0
  ]),
  [new DataElement("color", 3, gl.FLOAT, false, 0, 0)]
);
const iBuffer = new IndexBufferData(
  new Uint16Array([
    0,1,2, 0,2,3, 4,5,6, 4,6,7,
    8,9,10, 8,10,11, 12,13,14, 12,14,15,
    16,17,18, 16,18,19, 20,21,22, 20,22,23
  ])
);
vBuffer.create(gl);
cBuffer.create(gl);
iBuffer.create(gl);

engine._update = (gl) => {
  // console.log('--');
  gl.clearColor(0.0, 0.0, 0.0, 1.0);
  // 用上面指定的颜色清除缓冲区
  gl.clear(gl.COLOR_BUFFER_BIT);

  // 颜色 start 三
  colorProgram.bind();
  vBuffer.upload(colorProgram._glProgram, gl);
  cBuffer.upload(colorProgram._glProgram, gl);
  iBuffer.upload(gl);
  iBuffer.draw(gl);
};
